package it.progettoso.thread;


import it.progettoso.activity.LockScreenActivity;
import it.progettoso.utility.DBConnection;
import android.content.Context;
import android.content.Intent;
import android.os.PowerManager;
import android.widget.Toast;

public class ControlLockThread implements Runnable{
	private Context context;
	private int operation;
	DBConnection db=null;

	public ControlLockThread(Context context, int operation) {
		this.context=context;
		this.operation=operation;
		db = new DBConnection(context);
	}

	@Override
	public void run() {
		if(operation==0)
			writeLockOnDB("0");
		else if(operation==1)
			writeLockOnDB("1");
		else if(operation==2)
			CheckIfLocked();
	}


	public void writeLockOnDB (String Data){
		String myLockCode="";
		try{
			if(db==null)
				return;
			if(db.open()){
				myLockCode=db.readData(DBConnection.LOCK);
				if(myLockCode==null || myLockCode==""){
					db.insertData(DBConnection.LOCK, Data);
				}
				if(myLockCode!=null && !myLockCode.equals(Data)){
					db.updateData(DBConnection.LOCK, Data);
				}
				db.close();
			}

		}catch(Exception e){
			Toast.makeText(context, "ECCEZIONE Scrittura:" +e.fillInStackTrace(), Toast.LENGTH_SHORT).show();
		}
	}

	public String readLockFromDB(){
		String myLockCode=null;
		try{
			if(db==null)
				return null;
			if(db.open()){
				myLockCode = db.readData(DBConnection.LOCK);
				if(myLockCode==null || myLockCode==""){
					db.close();
					return null;
				}
				db.close();
			}
		}catch(Exception e){
			Toast.makeText(context, "ECCEZIONE Lettura:" +e.fillInStackTrace(), Toast.LENGTH_SHORT).show();
		}
		return myLockCode;
	}

	private void CheckIfLocked() {
		String myLockCode=readLockFromDB();

		if(myLockCode!=null && myLockCode.equals("1")){
			PowerManager pm = (PowerManager)context.getSystemService(Context.POWER_SERVICE);
			PowerManager.WakeLock wl = pm.newWakeLock(PowerManager.SCREEN_DIM_WAKE_LOCK
					| PowerManager.ACQUIRE_CAUSES_WAKEUP,
			"My Lock");
			wl.acquire();
			Intent lockintent = new Intent(context, LockScreenActivity.class);
			lockintent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
			context.startActivity(lockintent);
			wl.release();
			writeLockOnDB("1");
		}
	}
}
